﻿using AutoMapper;
using Castle.Core.Logging;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Enum;
using IntelligentAgriculture.Domain.Impl;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Domain.Interface.IColumnManagement;
using IntelligentAgriculture.Domain.Interface.IEarTagReposiotry;
using IntelligentAgriculture.Domain.Interface.Iridgepletype;
using IntelligentAgriculture.Domain.Interface.SheepFileModelInterface;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace IntelligentAgriculture.Services
{
    /// <summary>
    /// 羊只转舍服务实现
    /// </summary>
    public class SheepRescissionService : ISheepRescissionService
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SheepRescissionService> _logger;
        /// <summary>
        /// 羊只转舍仓储
        /// </summary>
        private readonly ISheepRescissionRepository _sheepRescissionRepository;
        /// <summary>
        /// 栋舍仓储
        /// </summary>
        private readonly IridegRepository _iridegRepository;
        /// <summary>
        /// 栏位仓储
        /// </summary>
        private readonly IColumnManRepository _columnManRepository;
        /// <summary>
        /// 数据库上下文
        /// </summary>
        private readonly AgricultureDbContext _db;
        /// <summary>
        /// 羊只档案仓储
        /// </summary>
        private readonly ISheepFileModelRepository _sheepFileModelRepository;
        /// <summary>
        /// 耳号仓储
        /// </summary>
        private readonly IEarTagReposiotry _earTagReposiotry;
        /// <summary>
        /// 种母断奶仓储
        /// </summary>
        private readonly ISheepAblactationRepository _sheepAblactationRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IUserRepository _userRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志</param>
        /// <param name="sheepRescissionRepository">羊只转舍仓储</param>
        /// <param name="iridegRepository">栋舍仓储</param>
        /// <param name="columnManRepository">栏位仓储</param>
        /// <param name="db">数据库上下文</param>
        /// <param name="sheepFileModelRepository">羊只档案仓储</param>
        /// <param name="earTagReposiotry">耳号仓储</param>
        /// <param name="sheepAblactationRepository">种母断奶仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="userRepository">用户仓储</param>
        public SheepRescissionService(ILogger<SheepRescissionService> logger, ISheepRescissionRepository sheepRescissionRepository, IridegRepository iridegRepository, IColumnManRepository columnManRepository, AgricultureDbContext db, ISheepFileModelRepository sheepFileModelRepository, IEarTagReposiotry earTagReposiotry, ISheepAblactationRepository sheepAblactationRepository, IMapper mapper, IUserRepository userRepository)
        {
            _logger = logger;
            _sheepRescissionRepository = sheepRescissionRepository;
            _iridegRepository = iridegRepository;
            _columnManRepository = columnManRepository;
            _db = db;
            _sheepFileModelRepository = sheepFileModelRepository;
            _earTagReposiotry = earTagReposiotry;
            _sheepAblactationRepository = sheepAblactationRepository;
            _mapper = mapper;
            _userRepository = userRepository;
        }
        /// <summary>
        /// 获取羊只转舍列表
        /// </summary>
        /// <returns>羊只转舍列表</returns>
        public async Task<PageOutput<SheepRescissionOutput>> GetSheepRescission(SheepRescissionInput input)
        {
            try
            {
                ///获取羊只转舍列表
                var list = await _sheepRescissionRepository.GetSheepRescission();
                // 获取栋舍表和栏位表
                var buildings = _iridegRepository.Showinfo();
                var columns = _columnManRepository.GetShow();
                //转舍开始日期查询
                if (!string.IsNullOrEmpty(input.sheepRescissionDateAction))
                {
                    list = list.Where(p => p.SheepRescissionDate >= DateTime.Parse(input.sheepRescissionDateAction)).ToList();
                }
                //转舍结束日期查询
                if (!string.IsNullOrEmpty(input.sheepRescissionDateEnd))
                {
                    list = list.Where(p => p.SheepRescissionDate <= DateTime.Parse(input.sheepRescissionDateEnd)).ToList();
                }
                //羊只耳号查询
                //使用 StringComparison.OrdinalIgnoreCase 进行不区分大小写的字符串匹配。
                if (!string.IsNullOrEmpty(input.earTag))
                {
                    list = list.Where(p => p.EarTag.Contains(input.earTag, StringComparison.OrdinalIgnoreCase)).ToList();
                }
                //转舍类型查询
                if (input.roundType > 0)
                {
                    list = list.Where(p => p.RoundType == input.roundType).ToList();
                }
                //转出栋舍查询
                if (input.OutBuildingManageId > 0)
                {
                    list = list.Where(p => p.OutBuildingManageId == input.OutBuildingManageId).ToList();
                }
                //转出栏位查询
                if (input.OutColumMangementId > 0)
                {
                    list = list.Where(p => p.OutColumMangementId == input.OutColumMangementId).ToList();
                }
                //转入栋舍查询
                if (input.ToBuildingManageId > 0)
                {
                    list = list.Where(p => p.ToBuildingManageId == input.ToBuildingManageId).ToList();
                }
                //转入栏位查询
                if (input.ToColumMangementId > 0)
                {
                    list = list.Where(p => p.ToColumMangementId == input.ToColumMangementId).ToList();
                }
                var newlist = (from sr in list
                               join bu in buildings
                               on sr.OutBuildingManageId equals bu.RidgepoleId
                               join co in columns
                               on sr.OutColumMangementId equals co.ColumnManagementId
                               select new SheepRescissionOutput()
                               {
                                   CreateName = sr.CreateName,
                                   CreateTime = sr.CreateTime,
                                   DocumentNumber = sr.DocumentNumber,
                                   EarTag = sr.EarTag,
                                   NowRidgepoleName = buildings.FirstOrDefault(p => p.RidgepoleId == sr.OutBuildingManageId).RidgepoleName,
                                   NowColumnName = columns.FirstOrDefault(p => p.ColumnManagementId == sr.OutColumMangementId).ColumnName,
                                   GoRidgepoleName = buildings.FirstOrDefault(p => p.RidgepoleId == sr.ToBuildingManageId).RidgepoleName,
                                   GOColumnName = columns.FirstOrDefault(p => p.ColumnManagementId == sr.ToColumMangementId).ColumnName,
                                   Isdel = sr.Isdel,
                                   OutBuildingManageId = sr.OutBuildingManageId,
                                   OutColumMangementId = sr.OutColumMangementId,
                                   ToBuildingManageId = sr.ToBuildingManageId,
                                   ToColumMangementId = sr.ToColumMangementId,
                                   RoundType = sr.RoundType,
                                   SheepRescissionDate = sr.SheepRescissionDate,
                                   SheepRescissionId = sr.SheepRescissionId,
                                   SheepRescissionSex = sr.SheepRescissionSex,
                                   SheepType = sr.SheepType,
                                   UpdateName = sr.UpdateName,
                                   UpdateTime = sr.UpdateTime,
                                   Variety = sr.Variety
                               });
                var result = new PageOutput<SheepRescissionOutput>()
                {
                    TotalCount = newlist.Count(),
                    PageSize = input.PageSize,
                    Data = newlist.OrderByDescending(p => p.CreateTime).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList()
                };
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError("获取羊只转舍列表失败：" + ex.Message);
                throw ex;
            }
        }
        /// <summary>
        /// 添加羊只转舍
        /// </summary>
        /// <param name="sheepRescissions">羊只转舍列表</param>
        /// <returns></returns>
        public async Task<int> AddSheepRescission(List<Sheeprescission> sheepRescissions)
        {
            using (var tran = _db.Database.BeginTransaction())
            {
                try
                {
                    foreach (var item in sheepRescissions)
                    {
                        //单据号为雪花Id
                        item.DocumentNumber = YitIdHelper.NextId().ToString();
                        item.SheepRescissionDate = DateTime.Now;
                        item.CreateTime = DateTime.Now;
                        item.UpdateTime = null;
                        item.UpdateName = null;
                        item.Isdel = false;
                        // 添加到种母断奶表
                    }
                    await _sheepRescissionRepository.AddSheepRescission(sheepRescissions);
                    await _db.SaveChangesAsync();
                    //循环添加羊只转舍
                    foreach (var item in sheepRescissions)
                    {
                        // 获取羊只档案
                        var sheepfile = await _sheepFileModelRepository.GetSheepfilemodels();
                        // 根据添加的羊只耳号修改羊只档案表数据
                        var sheep = sheepfile.FirstOrDefault(p => p.EarTag == item.EarTag);
                        if (sheep != null)
                        {
                            sheep.BuildingId = item.ToBuildingManageId;
                            sheep.ColumnId = item.ToColumMangementId;

                            await _sheepFileModelRepository.UpdaSheepFileModel(sheep);
                        }
                        _db.Sheepfilemodels.Update(sheep);
                        await _db.SaveChangesAsync();
                    }
                    //事务提交
                    tran.Commit();
                    return 1;
                }
                catch (Exception ex)
                {
                    // 日志记录失败信息
                    _logger.LogError("新增羊只转舍失败！" + ex.Message);
                    //事务回滚
                    tran.Rollback();
                    throw;
                }
            }
        }
        /// <summary>
        /// 获取档案表母羊在哺乳的耳号列表
        /// </summary>
        /// <returns>包含母羊在哺乳状态的耳号信息的列表</returns>
        public async Task<List<Eartag>> GetEweEarTagsFromSheepFile()
        {
            try
            {
                // 获取档案表里的耳号
                var sheepfile = await _sheepFileModelRepository.GetSheepfilemodels();
                //在场羊只
                sheepfile = sheepfile.Where(p => p.PresentState == 1 && p.IsDel == false);
                // 创建一个 string 类型的 list 集合用来存储查询到的耳号
                List<string> earTags = sheepfile.Select(s => s.EarTag).ToList()!;
                //获取所有耳号的信息
                var earTagDetails = await _earTagReposiotry.GetShow();
                // 根据 earTags 里的耳号，去耳号表获取对应耳号信息
                var matchingEarTags = earTagDetails.Where(e => earTags.Contains(e.EarTagNumber!)).ToList();
                // 返回在场的羊只的耳号信息的列表
                return matchingEarTags;
            }
            catch (Exception ex)
            {
                _logger.LogError("获取耳号列表失败！" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 删除羊只转舍
        /// </summary>
        /// <param name="userId"> 用户Id</param>
        /// <param name="ids"> 羊只转舍Id列表</param>
        /// <returns></returns>
        public async Task<int> DelSheepRescission(int userId, params int[] ids)
        {
            var res = await _sheepRescissionRepository.DelSheepRescission(userId, ids);
            return res;
        }
    }
}